package com.imooc.maokeyang.alllearning.controller;

import javax.validation.Valid;

import com.imooc.maokeyang.alllearning.domain.common.ResponseResult;
import com.imooc.maokeyang.alllearning.domain.dto.LoginDTO;
import com.imooc.maokeyang.alllearning.security.entity.JwtUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.imooc.maokeyang.alllearning.security.jwt.JwtTokenUtils;

import java.util.Collection;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class AuthController {
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    PasswordEncoder encoder;

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @PostMapping("/signin")
    public ResponseResult authenticateUser(@Valid @RequestBody LoginDTO loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        JwtUser jwtUser = (JwtUser)authentication.getPrincipal();

        Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();

        String role = "";
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }

        String token = jwtTokenUtils.generateJwtToken(jwtUser.getUsername(),
                                                        role, false);

//        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//        List<String> roles = userDetails.getAuthorities().stream()
//                .map(item -> item.getAuthority())
//                .collect(Collectors.toList());



        return ResponseResult.success(JwtTokenUtils.TOKEN_PREFIX + token);

    }
}